<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: #6ff;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];

    var scrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    var maxLeft = scrollWidth - box.clientWidth;
    var maxTop = scrollHeight - box.clientHeight;

    window.onresize = function () {
        var scrollWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
        var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        var maxLeft = scrollWidth - box.clientWidth;
        var maxTop = scrollHeight - box.clientHeight;
    }

    var obj = {
        target: document.getElementsByClassName("box")[0],
        dragStart: function () {
            var _this = this;
            this.target.onmousedown = function (e) {
                var e = e || window.event;
                var posX = e.offsetX;
                var posY = e.offsetY;
                _this.posX = posX;
                _this.posY = posY;
                _this.dragMove();
                _this.dragEnd();
            }
        },

        dragMove: function () {
            var _this = this;
            document.onmousemove = function (e) {
                var e = e || window.event;
                var x = e.pageX - _this.posX;
                var y = e.pageY - _this.posY;
                if (x < 0) x = 0;
                if (y < 0) y = 0;
                if (x > maxLeft) x = maxLeft;
                if (y > maxTop) y = maxTop;
                _this.target.style.left = x + "px";
                _this.target.style.top = y + "px";
            }
        },
        
        dragEnd: function () {
            document.onmouseup = function () {
                document.onmousemove = null;
            }
        }
    }

    obj.dragStart();
</script>

</html>